package com.gk.panda.apis.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gk.panda.apis.entity.TransectManager.dto.AddTransectDto;
import com.gk.panda.apis.entity.TransectManager.dto.TransectFileDto;
import com.gk.panda.apis.entity.TransectManager.dto.TransectListDto;
import com.gk.panda.apis.entity.TransectManager.entity.Properties;
import com.gk.panda.apis.entity.TransectManager.entity.TransectEntity;
import com.gk.panda.apis.entity.TransectManager.vo.TransectDetailsOfAppVo;
import com.gk.panda.apis.entity.TransectManager.vo.TransectFileVo;
import com.gk.panda.apis.entity.TransectManager.vo.TransectListVo;
import com.gk.panda.apis.log.Log;
import com.gk.panda.apis.service.OrgService;
import com.gk.panda.apis.service.TransectManagerService;
import com.gk.panda.commons.controller.BaseController;
import com.gk.panda.commons.page.TableDataInfo;
import com.gk.panda.commons.result.Result;
import com.gk.panda.commons.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName: TransectManagerCroller
 * @Description: 样线管理
 * @author: Sir.yang
 * @date: 2022/11/9 18:37
 * @version: 1.0
 **/
@RestController
@Api(tags = "样线管理")
@RequestMapping("/edmp/transect")
public class TransectManagerCroller extends BaseController{

    @Autowired
    private TransectManagerService transectManagerService;

    @Autowired
    private OrgService orgService;
    /**
     * ------------------APP-------------------------------
     **/

    @ApiOperation("获取APP样线列表 -无用")
    @GetMapping("/getListOfApp/{fkOrgId}")
    public Result<List<String>> getListOfApp(@PathVariable Integer fkOrgId) {
        return Result.ok(transectManagerService.getTransectListOfApp(fkOrgId));
    }

    @ApiOperation("获取APP样线详情 -无用")
    @GetMapping("/getDetailsOfApp/{transectId}")
    public Result<TransectDetailsOfAppVo> getDetailsOfApp(@PathVariable Integer transectId) {
        return Result.ok(transectManagerService.getTransectDetailsOfApp(transectId));
    }


    /**
     * ------------------PC-------------------------------
     **/
//    @ApiOperation("PC获取样线列表")
//    @PostMapping("/getList")
//    public Result<Page<TransectListVo>> getTransectList(@RequestBody TransectListDto dto) {
//        return Result.ok(transectManagerService.getTransectList(dto));
//    }

    @ApiOperation("PC新建样线")
    @Log
    @PostMapping("/addTransect")
    public Result<String> addTransect(AddTransectDto dto) throws IOException {

        if (null == dto.getFile())
        {
            return Result.error(400,"样线解析文件必传");
        }

//        //上传文件，获取url解析
//        String originalFilename = dto.getFile().getOriginalFilename();
//        String[] fileNameAttr = originalFilename.split("\\.");
//        //获取文件的后缀
//        String suffix = fileNameAttr[fileNameAttr.length - 1];
//        String url = fdfsService.uploadFile(dto.getFile(),suffix);

        //将文件转换为String
//        String geoJson = getStr(MultipartFileToFile(dto.getFile()));
//        System.out.println(geoJson);
        //解析文件中的属性
        BufferedReader br = new BufferedReader(new FileReader(MultipartFileToFile(dto.getFile())));
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        String sCurrentLine;
        int count =1;
        while ((sCurrentLine = br.readLine()) != null) {
            if(count >1){
                if(!"]}".equals(sCurrentLine)){
                    //json转对象
                    JSONObject jsonObject = JSONUtil.parseObj(StringEscapeUtils.unescapeJava(sCurrentLine));
                    TransectEntity transectEntity = JSONUtil.toBean(jsonObject, TransectEntity.class);
                    JSONObject jsonObjectPro = JSONUtil.parseObj(transectEntity.getProperties());
                    Properties properties = JSONUtil.toBean(jsonObjectPro, Properties.class);
                    //样线编号
                    if (StringUtils.isNotEmpty(properties.get样线编号())) {
                        transectEntity.setTransectSn(properties.get样线编号());
                    } else if (StringUtils.isNotEmpty(properties.get线路编号())){
                        transectEntity.setTransectSn(properties.get线路编号());
                    } else {
                        QueryWrapper<TransectEntity> wrapper = new QueryWrapper<>();
                        String abbr = orgService.getAbbrById(dto.getFkOrgId());
                        String lastSn = transectManagerService.getLastSnByOrgId(dto.getFkOrgId(),abbr+"YX");
                        String transectSn = null;
                        if (lastSn == null) {
                            transectSn = abbr + "YX0001";
                        } else {
                            String num = lastSn.substring(lastSn.length() - 4);
                            String str = lastSn.substring(0, lastSn.length() - 4);
                            int newNum = Integer.parseInt(num) + 1;
                            if (newNum > 999) {
                                transectSn = str + newNum;
                            } else if (newNum > 99) {
                                transectSn = str + "0" + newNum;
                            } else if (newNum > 9) {
                                transectSn = str + "00" + newNum;
                            } else {
                                transectSn = str + "000" + newNum;
                            }
                        }
                        transectEntity.setTransectSn(transectSn);
                    }
                    transectEntity.setCountyName(properties.get县名());
                    transectEntity.setOrgId(dto.getFkOrgId());
                    transectEntity.setOrgName(dto.getOrgName());
                    if (sCurrentLine.endsWith(",")){
                        transectEntity.setGeoJson(sCurrentLine.substring(0,sCurrentLine.length()-1));
                    } else {
                        transectEntity.setGeoJson(sCurrentLine);
                    }
                    transectEntity.setCreateBy(UserUtil.getCurrentUserName());
                    //设置样线类型为样线管理
                    transectEntity.setTranType("0");
                    //存样线
                    transectManagerService.addTransect(transectEntity);

                    //拼接文件样线，返回给前端显示
                    stringBuilder.append(sCurrentLine);
                }else{
                    stringBuilder.append("]");
                }
            }
            count++;
        }
        String result = String.valueOf(stringBuilder);
        return Result.ok(result);
    }

    @ApiOperation("PC查看样线详情包括json")
    @GetMapping("/getInfo/{id}")
    public Result<TransectFileVo> getTransectDetails(@PathVariable Integer id) {
        return Result.ok(transectManagerService.getTransectDetails(id));
    }

    @ApiOperation("PC删除样线")
    @Log
    @DeleteMapping("/remove/{transectId}")
    public Result<Integer> removeTransect(@PathVariable Integer transectId) {
        return Result.ok(transectManagerService.removeTransect(transectId));
    }

    @ApiOperation("启用禁用样线 -无用")
    @GetMapping("/enableDisable/{transectId}")
    public Result<Integer> enableDisable(@PathVariable Integer transectId) throws UnsupportedEncodingException {
        return Result.ok(transectManagerService.enableDisable(transectId));
    }

    @ApiOperation("查看样线列表")
    @PostMapping("/getTransList")
    public Result<TableDataInfo> getTransList(@Validated @RequestBody TransectFileDto transectFileDto) {
        startPage();
        return Result.ok(getDataTable(transectManagerService.getTransectList(transectFileDto)));
    }


    //将MultipartFile转换为File
    public File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        if (fileName == null){
            return null;
        }
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //把一个文件中的内容读取成一个String字符串
    public static String getStr(File jsonFile){
        String jsonStr;
        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
